package com.itheima.sh.util;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;

/*
    1.静态方法
    2.私有化构造方法
    3.位于util包
 */
public class SqlSessionUtil {
    //定义成员变量
    private static SqlSessionFactory sessionFactory;

    //静态代码块中
    static {
        try {
            //1.创建工厂创造类对象
            SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
            //2.获取工厂对象
            InputStream is = Resources.getResourceAsStream("mybatis-config.xml");
            sessionFactory = builder.build(is);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //定义静态方法
    //获取会话
    public static SqlSession getSqlSession() throws Exception {
        //3.获取会话对象
        SqlSession sqlSession = sessionFactory.openSession(true);
        //返回会话对象
        return sqlSession;
    }

    //获取工厂
    public static SqlSessionFactory getSqlSessionFactory() throws Exception {

        //返回工厂对象
        return sessionFactory;
    }
}
